package bb.lanxing.activity.bluetooth;

import android.content.ComponentName;
import android.os.Bundle;

import bb.lanxing.R;
import bb.lanxing.lib.devices.core.sync.SyncHelper;
import bb.lanxing.lib.devices.core.sync.SyncManager;
import bb.lanxing.lib.devices.core.sync.SyncService;
import bb.lanxing.manager.RemoteSharedPreference;
import bb.lanxing.manager.SPConstant;
import bb.lanxing.activity.base.BaseViewActivity;
import bb.lanxing.service.AppSyncService;

public abstract class BaseSyncActivity extends BaseViewActivity implements SyncHelper.SyncHelperCallback {
    public static final String EXTRA_SHOULD_RUNNING_IN_BACKGROUND = "extra_should_request_running_in_background";
    protected SyncHelper mSyncHelper;
    protected SyncManager mSyncManager;

    protected Bundle getArgs() {
        return null;
    }

    protected abstract String getSyncManagerName();

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
    }

    private void initSyncHelper() {
        String address = getAddress();
        String syncManagerName = getSyncManagerName();
        Bundle args = getArgs();
        ComponentName componentName = new ComponentName(this, AppSyncService.class);
        if (address == null || syncManagerName == null) {
            toast(R.string.params_error);
            finish();
            return;
        }
        this.mSyncHelper = new SyncHelper(componentName, address, syncManagerName, args, this);
    }

    public void bindSyncService() {
        initSyncHelper();
        if (this.mSyncHelper != null) {
            if (RemoteSharedPreference.getInstance().getBoolean(SPConstant.KEY_SYNC_SERVICE_FOREGROUND, true)) {
                this.mSyncHelper.startForgroundSyncService(this);
            }
            this.mSyncHelper.bindSyncService(this);
        }
    }

    public void unbindSyncService(boolean z) {
        SyncHelper syncHelper = this.mSyncHelper;
        if (syncHelper != null) {
            syncHelper.unbindSyncService(this, z);
        }
    }

    protected boolean shouldRunningInBackground() {
        return isSynchronising();
    }

    public String getAddress() {
        return getIntent().getStringExtra("EXTRA_DEVICE_ADDRESS");
    }

    public boolean isSynchronising() {
        SyncHelper syncHelper = this.mSyncHelper;
        return (syncHelper != null && syncHelper.isSynchronising()) || SyncHelper.isSynchronising(getSyncManagerName(), getAddress());
    }

    @Override
    public void onAttachedToSyncManager(SyncManager syncManager) {
        this.mSyncManager = syncManager;
    }

    @Override
    public void onDetachedFromSyncManager(SyncManager syncManager) {
        this.mSyncManager = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindSyncService(shouldRunningInBackground());
    }

    protected Class<? extends SyncService> getSyncServiceClass() {
        return AppSyncService.class;
    }
}
